package consumer_manager

import (
	"fmt"
	"time"
)

// Config 消费者管理器配置
type Config struct {
	// 基础配置
	ConsumerName        string        `json:"consumer_name"`        // 消费者名称
	ConsumerRemark      string        `json:"consumer_remark"`      // 消费者中文备注
	HostIP              string        `json:"host_ip"`              // 宿主机内网IP
	HostPort            string        `json:"host_port"`            // 宿主机映射端口
	ReportInterval      time.Duration `json:"report_interval"`      // 上报间隔，默认30秒
	MinConsumers        int           `json:"min_consumers"`        // 最小消费者数量，默认1
	MaxConsumers        int           `json:"max_consumers"`        // 最大消费者数量，默认100
	SpawnConsumerCount  int           `json:"spawn_consumer_count"` // 启动消费者数量
	DepthLimit          int           `json:"depth_limit"`          // 消息积压报警阈值
	
	// NSQ配置
	NSQLookupHost   string `json:"nsq_lookup_host"`   // NSQ Lookup地址
	NSQPubMsgHost   string `json:"nsq_pub_msg_host"`   // NSQ 发布消息地址
	NSQHTTPAddress  string `json:"nsq_http_address"`  // NSQ HTTP地址
	NSQAdminAddress string `json:"nsq_admin_address"` // NSQ Admin地址
	Topic           string `json:"topic"`             // NSQ Topic
	Channel         string `json:"channel"`           // NSQ Channel
	
	// HTTP服务配置
	HTTPEnabled     bool   `json:"http_enabled"`      // 是否启用HTTP服务
	HTTPPort        string `json:"http_port"`         // HTTP端口，固定18888
	HTTPPrefix      string `json:"http_prefix"`       // HTTP路由前缀，默认"/api/v1"
	
	// 数据库配置
	TableName       string `json:"table_name"`        // 数据库表名
}

// DefaultConfig 返回默认配置
func DefaultConfig() *Config {
	return &Config{
		ConsumerName:        getDefaultConsumerName(),
		ConsumerRemark:      getDefaultConsumerRemark(),
		HostIP:              getHostIP(),
		HostPort:            getHostPort(),
		ReportInterval:      30 * time.Second,
		MinConsumers:        1,
		MaxConsumers:        getMaxConsumers(),
		SpawnConsumerCount:  getSpawnConsumerCount(),
		DepthLimit:          getDepthLimit(),
		NSQLookupHost:       getNSQLookupHost(),
		NSQPubMsgHost:       getNSQPubMsgHost(),
		NSQHTTPAddress:      getNSQHTTPAddress(),
		NSQAdminAddress:     getNSQAdminAddress(),
		Topic:               getDefaultTopic(),
		Channel:         getDefaultChannel(),
		HTTPEnabled:     true,
		HTTPPort:        getAPIPort(),
		HTTPPrefix:      "/api/v1",
		TableName:       "tbl_consumer_monitor",
	}
}

// Validate 验证配置
func (c *Config) Validate() error {
	if c.ConsumerName == "" {
		return fmt.Errorf("consumer_name cannot be empty")
	}
	if c.HostIP == "" {
		return fmt.Errorf("host_ip cannot be empty")
	}
	if c.MinConsumers < 1 {
		return fmt.Errorf("min_consumers must be at least 1")
	}
	if c.MaxConsumers < c.MinConsumers {
		return fmt.Errorf("max_consumers must be greater than or equal to min_consumers")
	}
	if c.ReportInterval < time.Second {
		return fmt.Errorf("report_interval must be at least 1 second")
	}
	return nil
}